package com.aiju.cash.ui.login.manager;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;

import com.aiju.app.config.ConfigManager;
import com.aiju.bean.User;
import com.aiju.cash.core.api.DataJson;
import com.aiju.cash.core.api.LoginApi;
import com.aiju.cash.ui.login.CreateShopActivity;
import com.aiju.cash.ui.login.LoginActivity;
import com.aiju.cash.ui.main.MainActivity;
import com.aiju.common.ActivityStack;
import com.aiju.utils.L;
import com.aiju.utils.PreferencesUtils;
import com.aiju.utils.T;
import com.aiju.widgit.dialog.DialogHelper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zhy.http.okhttp.callback.StringCallback;

import okhttp3.Call;

/**
 * @author: 佐为
 * @date: 2016-11-25 11:06
 * @version: V1.0
 * @Description: 登录接口
 */
public class LoginManager {

    private Activity mActivity;

    private DialogHelper mDialogHelper;

    private boolean showDialog;

    private String userPassWord;

    public LoginManager(Activity mActivity, DialogHelper mDialogHelper, boolean dialog) {
        this.mActivity = mActivity;
        this.mDialogHelper = mDialogHelper;
        this.showDialog = dialog;
    }

    public LoginManager(Activity mActivity, DialogHelper mDialogHelper) {
        this(mActivity, mDialogHelper, true);
    }

    /**
     * 登录
     *
     * @param userName
     * @param userPassWord
     */
    public void login(String userName, String userPassWord) {
        if (showDialog) {
            mDialogHelper.showLoadingProgressDialog();
        }
        this.userPassWord = userPassWord;
        new LoginApi().login(userName, userPassWord, ConfigManager.getInstance().getRegId(), new LoginCallBack());
    }

    /**
     * 免登录
     *
     * @param userName
     * @param userPassWord
     */
    public void loginSSO(String userName, String userPassWord) {
        this.userPassWord = userPassWord;
        new LoginApi().login(userName, userPassWord, ConfigManager.getInstance().getRegId(), new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                T.ToastNetError();
                PreferencesUtils.putString(mActivity, "password", "");
                Intent intent = new Intent(mActivity, LoginActivity.class);
                mActivity.startActivity(intent);
            }

            @Override
            public void onResponse(String response, int id) {
                parseDate(response);
            }
        });
    }

    /**
     * 网络请求回调
     */
    private final class LoginCallBack extends StringCallback {
        @Override
        public void onError(Call call, Exception e, int id) {
            mDialogHelper.dismissProgressDialog();
            T.ToastNetError();
        }

        @Override
        public void onResponse(String response, int id) {
            mDialogHelper.dismissProgressDialog();
            parseDate(response);
        }
    }

    /**
     * 解析登录数据13738137546
     *
     * @param response
     */
    private void parseDate(String response) {
        DataJson dataJson = new DataJson(response);
        if (dataJson.isSuccess()) {
            User user = new Gson().fromJson(dataJson.getData().toString(), new TypeToken<User>() {
            }.getType());
            if (user == null) {
                T.ToastShort("暂时无法登录，请稍后重试");
                return;
            }

            if (!TextUtils.isEmpty(user.getStoreId()) && !user.getStoreId().equals("null")) {
                loginSuccess(user); //登录成功
            } else { //没有店铺
                Intent intent = new Intent(mActivity, CreateShopActivity.class);
                intent.putExtra("type", 1);
                intent.putExtra("user", user);
                intent.putExtra("password", userPassWord);
                mActivity.startActivity(intent);
            }
        } else {
            //登录失败
            T.ToastShort(dataJson.getMsg());
            PreferencesUtils.putString(mActivity, "password", "");
            mActivity.finish();
            Intent intent = new Intent(mActivity, LoginActivity.class);
            mActivity.startActivity(intent);
        }
    }

    /**
     * 登录成功
     *
     * @param user
     */
    private void loginSuccess(User user) {

        ConfigManager.getInstance().setUser(user);
        new LoginApi().jpushBind(user.getShop().getStoreId(), user.getOperatorId(),
                ConfigManager.getInstance().getRegId(), user.getPhone(), user.getToken(), new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        DataJson json = new DataJson(response);
                        if (json.isSuccess()) {
                            L.d("推送绑定成功");
                        } else {
                            L.e(json.getMsg());
                        }
                    }
                });

        ActivityStack.finishAll();
        Intent intent = new Intent(mActivity, MainActivity.class);
        mActivity.startActivity(intent);
        savaUser(user);
        String regId = ConfigManager.getInstance().getRegId();
        if (TextUtils.isEmpty(regId)) {
            return;
        }

    }

    public void loginOut(User mUser) {
        new LoginApi().logout(mUser.getToken(), ConfigManager.getInstance().getRegId(), new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                T.ToastNetError();
            }

            @Override
            public void onResponse(String response, int id) {
                DataJson dataJson = new DataJson(response);
                if (dataJson.isSuccess()) {
                    T.ToastShort("注销成功");
                    //PreferencesUtils.putString(UserActivity.this, "name", "");
                    PreferencesUtils.putString(mActivity, "password", "");
                    ActivityStack.finishAll();
                    Intent intent = new Intent(mActivity, LoginActivity.class);
                    mActivity.startActivity(intent);
                } else {
                    T.ToastShort("注销失败");
                    L.e(dataJson.getMsg());
                }
            }
        });
    }

    /**
     * 保存用户
     */
    private void savaUser(User user) {
        PreferencesUtils.putString(mActivity, "name", user.getPhone());
        PreferencesUtils.putString(mActivity, "password", userPassWord);
    }
}
